package com.example.shw

import android.media.AudioAttributes
import android.media.SoundPool
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Gravity
import android.widget.Button
import android.widget.LinearLayout

class SoundPoolActivity : AppCompatActivity() {
    private lateinit var soundPool: SoundPool
    private var soundMap: HashMap<Int, Int> = HashMap()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val linearLayout = LinearLayout(this)
        linearLayout.orientation = LinearLayout.VERTICAL
        linearLayout.gravity = Gravity.CENTER_VERTICAL
        val button1 = Button(this)
        button1.text = "1"
        val button2 = Button(this)
        button2.text = "2"
        val button3 = Button(this)
        button3.text = "3"
        linearLayout.addView(button1)
        linearLayout.addView(button2)
        linearLayout.addView(button3)
        setContentView(linearLayout)

        val attr = AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_GAME)//设置音效使用场景
                //设置音效类型
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()
        soundPool = SoundPool.Builder()
            .setAudioAttributes(attr)//设置音效池的属性
            .setMaxStreams(10)//设置最多可容纳10个音频流
            .build()
        //使用load方法加载指定的音频文件，并返回所加载的音频ID
        //此处使用HashMap来管理这些音频流
        soundMap[1] = soundPool.load(this, R.raw.enemy1_down, 1)
        soundMap[2] = soundPool.load(this, R.raw.enemy2_down, 1)
        soundMap[3] = soundPool.load(this, R.raw.enemy3_down, 1)

        button1.setOnClickListener {
            soundPool.play(soundMap[1]!!, 1f, 1f, 0, 0, 1f)
        }
        button2.setOnClickListener {
            soundPool.play(soundMap[2]!!, 1f, 1f, 0, 0, 1f)
        }
        button3.setOnClickListener {
            soundPool.play(soundMap[2]!!, 1f, 1f, 0, 0, 1f)
        }
    }
}